package utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.provider.SyncStateContract;

/**
 * sp存储工具类
 * author:wbin
 *
 */
public class SpUtils {

	public static final String FIRST_START = "first_start";
	private static SharedPreferences sp;

	public SpUtils(Context context) {
		sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
	}

	/**
	 * 保存数据
	 * @param key
	 * @param value
	 */
	public void save(String key, Object value) {
		if(value == null || value instanceof String) {
			sp.edit().putString(key, (String) value).commit();
		} else if(value instanceof Integer) {
			sp.edit().putInt(key, (Integer) value).commit();
		} else if(value instanceof Boolean) {
			sp.edit().putBoolean(key, (Boolean) value).commit();
		} else {
			throw new RuntimeException();
		}
	}

	/**
	 * 获得数据
	 * @param key
	 * @param defaultValue
	 * @param <T>
	 * @return
	 */
	public <T> T get(String key, T defaultValue) {
		if(defaultValue == null || defaultValue instanceof String) {
			return (T) sp.getString(key, (String) defaultValue);
		} else if(defaultValue instanceof Integer) {
			return (T)(Integer)sp.getInt(key, (Integer) defaultValue);
		} else if(defaultValue instanceof Boolean) {
			return (T)(Boolean)sp.getBoolean(key, (Boolean) defaultValue);
		} else {
			throw new RuntimeException();
		}
	}

	/**
	 * 移除数据
	 * @param key
	 */
	public void remove(String key) {
		sp.edit().remove(key).commit();
	}
	
	
	/**
	 * 获取软件保存的参数
	 * @param contex
	 *  上下文
	 * @param key
	 * 取出参数的key
	 * @return
	 */
	public static boolean getBoolean(Context contex, String key) {
		if (sp == null) {
			sp = contex.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		return sp.getBoolean(key, false);// 默认返回false
	}

	/**
	 * 保存boolean类型的软件参数
	 * @param contex
	 * @param key
	 * @param values
	 * 要保存的值
	 */
	public static void setBoolean(Context contex, String key, boolean values) {
		if (sp == null) {
			sp = contex.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		sp.edit().putBoolean(key, values).commit();
	}
	
	/**
	 * 取出String类型的值
	 * @param context
	 * @param key
	 *
	 */
	public static String getString(Context context, String key){
		if (sp == null) {
			sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		return sp.getString(key, null);
	}
	
	/**
	 * 存入String类型的值
	 * @param context
	 * @param key
	 * @param values
	 */
	public static void setString(Context context, String key, String values) {
		if (sp == null) {
			sp = context.getSharedPreferences("config", Context.MODE_PRIVATE);
		}
		sp.edit().putString(key, values).commit();
	}
}
